package com.mazegame.backend;

import com.mazegame.backend.DBUtils;
import com.google.gson.Gson;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class BackendRegisterService {

    public static String register(String username, String password) {
        Map<String, String> response = new HashMap<>();

        // 验证用户名是否已存在
        if (isUsernameExists(username)) {
            response.put("status", "error");
            response.put("code", "username_exists");
            response.put("message", "用户名已存在");
            return new Gson().toJson(response);
        }

        // 插入新用户
        try (Connection conn = DBUtils.getConnection()) {
            String sql = "INSERT INTO users (username, password, score) VALUES (?, ?, 0)";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);

            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                // 注册成功
                response.put("status", "success");
                response.put("message", "注册成功");
            } else {
                // 注册失败
                response.put("status", "error");
                response.put("code", "registration_failed");
                response.put("message", "注册失败，请稍后再试");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.put("status", "error");
            response.put("code", "database_error");
            response.put("message", "数据库操作失败");
        }

        return new Gson().toJson(response);
    }

    private static boolean isUsernameExists(String username) {
        try (Connection conn = DBUtils.getConnection()) {
            String sql = "SELECT COUNT(*) FROM users WHERE username = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                int count = rs.getInt(1);
                return count > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return false;
    }
}
